const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

let db = cloud.database()

// 获取openId云函数入口函数
exports.main = async (event, context) => {
  // 获取基础信息
  const wxContext = cloud.getWXContext();
  let info = '';
  let edgeInfo = [];
  let openid = event.openid || wxContext.OPENID;
  let result = await db.collection('user_info').where({
	  openid:openid
  }).get();
  if(result.data.length===0){
	  info = {
		  		  openid:openid,
		  		  username:openid,
		  		  avatar:'HeadPortrait.jpg',
		  		  Signature:'BLACKPINK IN YOU AREA',
				  edgeCount:0,
				  fans:0,
				  follows:0,
				  insAccount:'',
				  insPassword:''
		  }
	  db.collection('user_info').add({
		  data:info
	  })
  }else{
	  console.log(result.data[0]);
	  info = result.data[0];
	  let edgeInfos = await db.collection('user_edge').where({
	  	  shortcode: info.openid
	  }).orderBy('taken_at_timestamp','desc').limit(12).get();
	  edgeInfo.push(...edgeInfos.data);
  }
  return {
    unionid: '',
	info:info,
	edgeInfo:edgeInfo
  };
};
